package com.jotta.client;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.jotta.client.communicate.Configuration;
import com.jotta.client.communicate.ServerCommunicator;
import com.jotta.client.dataaccess.DataAccess;
import com.jotta.client.exception.NetworkException;
import com.jotta.client.exception.ServerException;
import com.jotta.client.setting.ModeOfApplication;
import com.jotta.client.setting.SettingManager;
import com.jotta.client.utility.Utility;

public class StartUp extends Activity implements Runnable {
	ServerCommunicator communicator;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_up);

		Configuration.prepareConfiguration(this);

		// Start new thread to check & initialize parameters & show progress bar
		Thread thread = new Thread(this);
		thread.start();
	}

	/*
	 * Log in to server & notified to handler when finished
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		Bundle bundle = new Bundle();
		Message msg = new Message();

		if (DataAccess.getInstance().checkSDCardIsMounted())
			Configuration.setModeOfApplication(ModeOfApplication.FULL_OPTION);
		else
			Configuration.setModeOfApplication(ModeOfApplication.BROWSE);

		boolean autoLogin = SettingManager.getInstance().getAutoLogin();
		String username = SettingManager.getInstance().getUsername();
		String password = SettingManager.getInstance().getPassword();
		// String latestPath =
		// SettingManager.getInstance().getLatestBrowsePath();

		if (autoLogin && username != "" && password != "") {
			String message = logIn(username, password);
			// String message = restart(username, password, latestPath);
			bundle.clear();
			bundle.putString(Configuration.SERVER_MESSAGE_KEY, message);
			msg.setData(bundle);
			finishedloginHandler.sendMessage(msg);
		} else {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			startLoginActivityHandler.sendEmptyMessage(0);
		}
	}

	/**
	 * Log in
	 * 
	 * @return Message from server
	 */
	private String logIn(String username, String password) {
		try {
			// log in
			communicator = ServerCommunicator.getInstance();
			communicator.logIn(username, password);

			return Configuration.GET_DATA_SUCCESSFUL_MESSAGE;
		} catch (ServerException e) {
			return e.getErrorMessage();
		} catch (NetworkException e) {
			return e.getErrorMessage();
		} catch (Exception e) {
			if (e.getMessage() != null)
				return e.getMessage();
			return e.toString();
		}
	}

	/**
	 * Restart
	 * 
	 * @return Message from server
	 */
	@SuppressWarnings("unused")
	private String restart(String username, String password, String latestPath) {
		try {
			// log in
			communicator = ServerCommunicator.getInstance();
			communicator.restart(username, password, latestPath);

			return Configuration.GET_DATA_SUCCESSFUL_MESSAGE;
		} catch (ServerException e) {
			return e.getErrorMessage();
		} catch (NetworkException e) {
			return e.getErrorMessage();
		} catch (Exception e) {
			if (e.getMessage() != null)
				return e.getMessage();
			return e.toString();
		}
	}

	/** start login activity handler */
	private Handler startLoginActivityHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				// start new activity
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), Login.class);
				startActivity(intent);
				finish();
			} catch (Exception e) {
				Utility.getAlertDialog(getApplicationContext(),
                        Configuration.getRes(), e.getMessage()).show();
			}
		}
	};

	/** When Log in finished dismiss progress dialog and start ListItem Activity */
	private Handler finishedloginHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String message = msg.getData().getString(
					Configuration.SERVER_MESSAGE_KEY);
			if (!message.equals(Configuration.GET_DATA_SUCCESSFUL_MESSAGE)) {
				Utility.getAlertDialog(StartUp.this, Configuration.getRes(),
                        message).show();
			} else {
				try {
					// start new activity
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), ListItem.class);
					startActivity(intent);
					finish();
				} catch (Exception e) {
					Utility.getAlertDialog(getApplicationContext(),
                            Configuration.getRes(), e.getMessage()).show();
				}
			}
		}
	};
}